package com.example.intermingle.service;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.intermingle.Constants;
import com.example.intermingle.dto.JqGridPageDto;
import com.example.intermingle.dto.UserEditDto;
import com.example.intermingle.dto.userDto;
import com.example.intermingle.mapper.RoleMapper;
import com.example.intermingle.mapper.UserMapper;
import com.example.intermingle.util.CommonUtils;
import com.example.intermingle.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@Service
public class UserService implements UserDetailsService {

    @Autowired
     UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    /**
     *
     * @param userCode //用户账号信息
     * @return 返回用户权限信息
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userCode) throws UsernameNotFoundException {
        //根据账号查询用户信息
        userDto user=userMapper.selectOneByUserCode(userCode);
        //判断数据不为空，为空就抛出异常
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //根据用户id来查询权限，然后放到dto
        user.setRoles(roleMapper.selectRole(user.getUserId()));
        //返回user权限信息
        return user;
    }

    /**
     * 查询所有的用户信息
     * @param page  当前页数
     * @param size   条数
     * @param userId  用户id
     * @param userName
     * @param userCode
     * @return
     */

    public JqGridPageDto<User> selectAllUser(Integer page, Integer size,  Integer userId,  String userName,  String userCode) {
        if (page != null && size != null) {
            page = (page - 1) * size;
        }
        //根据条件查询所有用户信息
        List<User> users=userMapper.selectAllByUserIdAndUserNameAndUserCode(page,size,userId,userName,userCode);
        //获取总页数
        Long records=userMapper.getTotal(userId,userName,userCode);
        //定义一个对象
        JqGridPageDto<User> userJqGridPageDto=new JqGridPageDto<>();
        //赋值
        userJqGridPageDto.setRows(users);
        userJqGridPageDto.setRecords(records);
        return userJqGridPageDto;
    }

    /**
     * 用户添加数据
     * @param userPassword 密码
     * @param userName 用户名
     * @param userCode 用户账号
     * @param userImg 用户头像
     * @return
     */
    public JqGridPageDto<User> addUser(String userPassword, String userName, String userCode, String userImg) {


        //定义一个对象
        JqGridPageDto<User> userJqGridPageDto=new JqGridPageDto<>();
        //判断用户账号是否为空
        if(!userCode.isEmpty()){
         //  根据用户账号查询*
            userDto user=userMapper.selectOneByUserCode(userCode);
            //用户数据判断是否为空，不为空就直接返回
            if(user!=null){
                //赋值
                userJqGridPageDto.setErrorMsg(Constants.FAILCode.ADD_EXISTS_FAIL);
                //返回数据
                return  userJqGridPageDto;
            }
        }

        //顶一个对象，然后赋值
        User user=new User();
        user.setUserPassword(CommonUtils.encryptionPassWord(userPassword));
        user.setUserName(userName);
        user.setUserCode(userCode);
        user.setUserImg(userImg);
        user.setCreatedBy(CommonUtils.getName());
        user.setUpdateBy(CommonUtils.getName());
        user.setCreatedDate(new Date());
        user.setUpdateDate(new Date());
        //插入用户数据
        int count= userMapper.insertAll(user);
        //判断是否成功
        if(count==1){
            //赋值
            userJqGridPageDto.setErrorMsg(Constants.SUCCESSCode.ADD_SUCCESS);
        }else{
            //赋值
            userJqGridPageDto.setErrorMsg(Constants.FAILCode.ADD_FAIL);
        }
        //返回数据
        return userJqGridPageDto;
    }

    /**
     * 更改用户
     * @param userEditDto 用户对象
     * @return
     */
    public JqGridPageDto<User> updateUser(UserEditDto userEditDto){
        //定义一个对象
        JqGridPageDto<User> userJqGridPageDto=new JqGridPageDto<>();
        //用用户id来查询用户信息
        User users=userMapper.selectOneByUserId(userEditDto.getUserId());
        //校验密码的是否一致
        Boolean userx= CommonUtils.decryptPassWord(userEditDto.getUserPassword(),users.getUserPassword());
        //不一致，直接返回结果
        if(!userx){
            userJqGridPageDto.setErrorMsg(Constants.FAILCode.INCONSISTENT_PASSWORDS);
            return userJqGridPageDto;
        }
        //定义一个用户对象
        User user =new User();
        //传过来的新密码不为空
        if(CommonUtils.isNotNull(userEditDto.getUserNewPassword())){
            //新密码赋值和加密
            user.setUserPassword(CommonUtils.encryptionPassWord(userEditDto.getUserNewPassword()));
        }
        //赋值
        user.setUserName(userEditDto.getUserName());
        user.setUserImg(userEditDto.getUserImg());
        user.setUserId(userEditDto.getUserId());
        //更新操作人员
        user.setUpdateBy(CommonUtils.getName());
        //更新操作时间
        user.setUpdateDate(new Date());
        //插入用户数据
        int count= userMapper.updateUser(user);
        //判断是否成功
        if(count==1){
            //赋值
            userJqGridPageDto.setErrorMsg(Constants.SUCCESSCode.UPDATE_SUCCESS);
        }else{
            //赋值
            userJqGridPageDto.setErrorMsg(Constants.FAILCode.UPDATE_FAIL);
        }
        return userJqGridPageDto;
    }

    /**
     * 根据用户id删除用户
     * @param userId
     * @return
     */
    public JqGridPageDto<User> delUser(Integer userId){
        //定义一个对象
        JqGridPageDto<User> userJqGridPageDto=new JqGridPageDto<>();
        int count= userMapper.delByUserId(userId);
        if(count==1){
            //赋值
            userJqGridPageDto.setErrorMsg(Constants.SUCCESSCode.DELECT_SUCCESS);
        }else{
            //赋值
            userJqGridPageDto.setErrorMsg(Constants.FAILCode.DELECT_FAIL);
        }
        return userJqGridPageDto;

    }

    /**
     * 导入用户数据
     * @param request
     * @return
     */
    public JqGridPageDto<User> imporUser(HttpServletRequest request) {
        //定义一个对象
        JqGridPageDto<User> userJqGridPageDto=new JqGridPageDto<>();
        //定义一个MultipartHttpServletRequest对象
        MultipartHttpServletRequest multipartRequest =null;
        //判断里面有没有文件
        if (request instanceof MultipartHttpServletRequest) {
            multipartRequest = (MultipartHttpServletRequest)(request);
        }
        //统计导入成功数
        int successCount=0;
        //统计导入失败数
        int failCount=0;
        //获取文件流，写入list集合
        List<MultipartFile> files = multipartRequest.getFiles("file");
        //存在多个文件，用for循环
        for(int i=0;i<files.size();i++){
            try {
                //写入字节输入流
                InputStream inputStream=files.get(i).getInputStream();
                ExcelReader excelReader=ExcelUtil.getReader(inputStream,"sheet1");
                //加入表头名称和封装对象的名称
                excelReader.addHeaderAlias("用户名称","userName");
                excelReader.addHeaderAlias("用户账号","userCode");
                excelReader.addHeaderAlias("用户密码","userPassword");
                excelReader.addHeaderAlias("用户头像","userImg");
                //获取文档的内容
                List<User> users=excelReader.readAll(User.class);
                //校验导入数据
                String error=checkUserImport(users);
                if(!users.equals(null)){
                    userJqGridPageDto.setErrorMsg(error);
                    return  userJqGridPageDto;
                }
                for(int j=0;j<users.size();j++){
                    //顶一个对象，然后赋值
                    User user=new User();
                    user.setUserPassword(CommonUtils.encryptionPassWord(users.get(j).getUserPassword()));
                    user.setUserName(users.get(j).getUserName());
                    user.setUserCode(users.get(j).getUserCode());
                    user.setUserImg(users.get(j).getUserImg());
                    user.setCreatedBy(CommonUtils.getName());
                    user.setUpdateBy(CommonUtils.getName());
                    user.setCreatedDate(new Date());
                    user.setUpdateDate(new Date());
                    int count= userMapper.insertAll(user);
                    //插入成功
                    if(count==1){
                        //成功次数加1
                       successCount=successCount+1;
                    }else{
                        //失败次数加1
                        failCount=failCount+1;
                    }
                }
                userJqGridPageDto.setErrorMsg("导入数"+(successCount+failCount)+"成功条数"+successCount+"失败条数"+failCount);
            }catch (Exception e){
                userJqGridPageDto.setErrorMsg("导入失败");
            }
        }
        return userJqGridPageDto;
    }

    /**
     *用户导出
     * @param page
     * @param size
     * @param response
     */
    public void exportUser(Integer page, Integer size,HttpServletResponse response) {
        if (page != null && size != null) {
            page = (page - 1) * size;
        }
        List<User> user=userMapper.selectAllByUserIdAndUserNameAndUserCode(page,size,null,null,null);
        //模板名称
       String fileName=Constants.TEMPLATE_EXPORT_USER;
        //创建一个ExcelWriter
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //给字段标值
        writer.addHeaderAlias("userId","用户id");
        writer.addHeaderAlias("userCode","用户账号");
        writer.addHeaderAlias("userName","用户名称");
        writer.addHeaderAlias("userPassword","用户密码");
        writer.addHeaderAlias("createdBy","创建人员");
        writer.addHeaderAlias("updateBy","更新人员");
        writer.addHeaderAlias("createdDate","创建时间");
        writer.addHeaderAlias("updateDate","修改时间");
        writer.addHeaderAlias("userImg","用户头像");
        writer.addHeaderAlias("validFlag","");
        writer.write(user, true);
        try {
            // 获取我们的输出流
            final OutputStream output = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";filename*=utf-8''"
                    + URLEncoder.encode(fileName, Constants.CODING_UTF8));
            writer.flush(output, true);
            writer.close();
            output.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 校验用户导入数据
     * @return
     */
    private String checkUserImport(List<User> user){
        //用户账号错误信息
        String UserCodeError="";
        //用户密码错误信息
        String UserPasswordeError="";
        for(int i=0;i<user.size();i++){
            if (!CommonUtils.isNotNull(user.get(i).getUserCode())){
                UserCodeError=Constants.importCheck.USERIMPORT_USER_CODE;
            }
            if (!CommonUtils.isNotNull(user.get(i).getUserPassword())){
                UserPasswordeError=Constants.importCheck.USERIMPORT_USER_PASSWORD;
            }

        }
        //两个错误信息都没有。直接返回null
        if(!UserCodeError.isEmpty()&&!UserPasswordeError.isEmpty()){
            return  UserCodeError+UserPasswordeError;
        }
        return   null;

    }
}
